﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace Company.Shell.Controls
{
    /// <summary>
    /// Fan.xaml 的交互逻辑
    /// </summary>
    public partial class Fan : UserControl
    {
        private Brush closeBrush;
        private Brush openBrush = new SolidColorBrush(Color.FromRgb(75, 169, 69));
        private Brush errorBrush = new SolidColorBrush(Color.FromRgb(220, 53, 69));
        private Brush grayBrush = new SolidColorBrush(Color.FromRgb(128, 128, 128));
        private DoubleAnimation rotationAnimation;

        public Fan()
        {
            InitializeComponent();
            closeBrush = _statusBorder.Background;// 保存初始背景色
            InitializeAnimation();
        }

        /// <summary>
        /// 风扇状态：0=停止(灰色)，1=正常运行(绿色)，2=故障(红色停止)
        /// </summary>
        public int State
        {
            get { return (int)GetValue(StateProperty); }
            set { SetValue(StateProperty, value); }
        }

        public static readonly DependencyProperty StateProperty =
            DependencyProperty.Register("State", typeof(int), typeof(Fan),
                new PropertyMetadata(0, new PropertyChangedCallback(StateChangedCallback)));

        private static void StateChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (Fan)d;
            if (control == null) return;

            if (e.NewValue is int state)
            {
                control.UpdateFanState(state);
            }
        }

        /// <summary>
        /// 风扇是否运行
        /// </summary>
        public bool IsRunning
        {
            get { return (bool)GetValue(IsRunningProperty); }
            set { SetValue(IsRunningProperty, value); }
        }

        public static readonly DependencyProperty IsRunningProperty = 
            DependencyProperty.Register("IsRunning", typeof(bool), typeof(Fan), 
                new PropertyMetadata(false, new PropertyChangedCallback(IsRunningChangedCallback)));

        private static void IsRunningChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (Fan)d;
            if (control == null) return;

            if (e.NewValue is bool isRunning)
            {
                // 当通过IsRunning属性改变时，自动更新State
                if (isRunning)
                {
                    control.State = 1; // 设置为正常运行状态
                }
                else
                {
                    control.State = 0; // 设置为停止状态
                }
            }
        }

        /// <summary>
        /// 风扇转速 (RPM)
        /// </summary>
        public int Speed
        {
            get { return (int)GetValue(SpeedProperty); }
            set { SetValue(SpeedProperty, value); }
        }

        public static readonly DependencyProperty SpeedProperty =
            DependencyProperty.Register("Speed", typeof(int), typeof(Fan), 
                new PropertyMetadata(0, new PropertyChangedCallback(SpeedChangedCallback)));

        private static void SpeedChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (Fan)d;
            if (control == null) return;

            if (e.NewValue is int speed)
            {
                control._speedText.Text = $"{speed} RPM";
                control.UpdateRotationSpeed(speed);
            }
        }

        private record FanStateConfig(Brush Background, string Text, Action RotationAction, string ColorHex);// 颜色十六进制字符串

        private void UpdateFanState(int state)
        {
            var config = state switch
            {
                0 => new FanStateConfig(grayBrush, "OFF", StopRotation, "#808080"),      // 停止状态 - 灰色
                1 => new FanStateConfig(openBrush, "ON", StartRotation, "#4080c0"),     // 正常运行状态 - 绿色
                2 => new FanStateConfig(errorBrush, "ERR", StopRotation, "#c05050"),    // 故障状态 - 红色，停止转动
                _ => new FanStateConfig(grayBrush, "OFF", () => State = 0, "#808080")   // 默认状态
            };

            _statusBorder.Background = config.Background;
            _statusText.Text = config.Text;
            config.RotationAction();// 执行对应的旋转动作
            UpdateFanBladeColor(config.ColorHex);// 更新叶片颜色
        }

        private void UpdateFanBladeColor(string colorHex)
        {
            var color = (Color)ColorConverter.ConvertFromString(colorHex);
            var brush = new SolidColorBrush(color);
            
            // 更新所有叶片的颜色
            foreach (var child in _fanBlades.Children)
            {
                if (child is System.Windows.Shapes.Path path)// 假设叶片是Path元素
                {
                    path.Fill = brush;
                }
            }
        }

        private void InitializeAnimation()// 初始化旋转动画
        {
            rotationAnimation = new DoubleAnimation()
            {
                From = 0,
                To = 360,
                Duration = TimeSpan.FromSeconds(2),
                RepeatBehavior = RepeatBehavior.Forever
            };
        }

        private void StartRotation()// 开始旋转
        {
            if (Speed > 0 && State == 1) // 只有在正常状态下才能旋转
            {
                _rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotationAnimation);
            }
        }

        private void StopRotation()// 停止旋转
        {
            _rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null);
            _rotateTransform.Angle = 0;
        }

        private void UpdateRotationSpeed(int speed)// 根据转速调整旋转速度
        {
            if (speed > 0 && State == 1) // 只有在正常状态下才能旋转
            {
                // 根据转速调整动画速度，转速越高动画越快
                double duration = Math.Max(0.2, 3.0 - (speed / 1000.0) * 2.5);
                rotationAnimation.Duration = TimeSpan.FromSeconds(duration);
                
                // 重新开始动画
                _rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotationAnimation);
            }
            else
            {
                StopRotation();
            }
        }
    }
}
